import 'package:flutter/material.dart';
import 'package:harmonyhive_flutter/pages/home/index.dart';
import 'package:harmonyhive_flutter/pages/mine/index.dart';
import 'package:harmonyhive_flutter/utils/evenbus.dart';
import 'package:harmonyhive_flutter/utils/toast.dart';
import 'package:harmonyhive_flutter/utils/token.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  // 记录当前索引
  int currentIndex = 0;

  // 底部TabBar数据数组 - 好处:后面还有页面在数组里面添加即可
  List tabBarList = [
    {
      "title": "首页",
      "default": "assets/tabs/home_default.png",
      "active": "assets/tabs/home_active.png",
    },
    {
      "title": "我的",
      "default": "assets/tabs/my_default.png",
      "active": "assets/tabs/my_active.png",
    },
  ];

  @override
  void initState() {
    super.initState();
    // 先获取token
    // delayed - 延迟 -0秒
    Future.delayed(Duration.zero, () async {
      final token = TokenManager();
      await token.init();
      print(TokenManager().getToken());
      // ToastUtil.showSuccess(TokenManager().getToken()!);
    });

    // 注册跳跳转到登录页的通知接收
    eventBus.on<LogoutEvent>().listen((event) {
      // 跳转登录页面
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        // 安卓 - 安全区
        // tabBar的索引值
        index: currentIndex,
        children: [
          const HomePage(),
          MinePage(currentIndex: currentIndex),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        // 设置底部导航item的样式
        type: BottomNavigationBarType.fixed,
        items: barItemList(),
        currentIndex: currentIndex,
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.black,
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }

  // 提供一个底部导航条数组:
  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    // 遍历:
    for (var item in tabBarList) {
      // 添加:
      items.add(
        BottomNavigationBarItem(
          icon: Image.asset(item['default'], width: 32, height: 32),
          activeIcon: Image.asset(item['active'], width: 32, height: 32),
          label: item['title'],
        ),
      );
    }
    // 返回数据:
    return items;
  }
}
